<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-5-11
 * Time: 9:11
 */

namespace app\manage\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\common\model\ProjectCategory;
use think\Db;
use app\common\model\Package as Package_Model;
use app\common\model\PackageItem as Item_Model;
use app\common\model\Goods as Goods_Model;
use app\common\model\Project as Project_Model;

class Package extends Admin
{

    /**
     * 套餐列表
     * @return mixed
     * @throws \think\Exception
     */
    public function index(){
        // 读取数据
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder();
        // 数据列表
        $data_list = Package_Model::where($map)->order($order)->paginate();
        // 分页数据
        $page = $data_list->render();

        $btn_add = [
            'title' => '新增套餐',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-info',
            'href' => url('add'),
        ];

        $btn_edit = [
            'title' => '修改套餐',
            'icon' => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-info btn-sm',
            'href' => url('edit',['id'=>"__id__"]),
        ];

        $btn_item = [
            'title' => '添加包含项目或者商品',
            'icon' => 'fa fa-fw fa-scribd',
            'class' => 'btn btn-info btn-sm',
            'href' => url('addItem',['id'=>"__id__"]),
        ];

        $btn_item_list = [
            'title' => '查看包含的项目或者商品列表',
            'icon' => 'fa fa-fw fa-sitemap',
            'class' => 'btn btn-info btn-sm',
            'href' => url('itemLists',['id'=>"__id__"]),
        ];

        //设置页面
        return ZBuilder::make('table')
            ->addColumn('id', 'ID', 'text')
            ->addColumn('sort', '排序', 'text')
            ->addColumn('name', '套餐名称', 'text')
            ->addColumn('price', '项目价格', 'text')
            ->addColumn('right_button', '操作', 'btn')
            ->setTableName('qt_data_package')// 指定数据表名
            ->addTopButton('add', $btn_add)// 添加顶部按钮
            ->addRightButton('edit', $btn_edit)// 添加顶部按钮
            ->addRightButton('item', $btn_item)// 添加顶部按钮
            ->addRightButton('lists', $btn_item_list)// 添加顶部按钮
            ->addTopButton('delete')
            ->setPrimaryKey('id')// 设置主键名为username
            ->setPageTitle('套餐列表')
            ->setRowList($data_list)// 设置表格数据
            ->setPages($page)// 设置分页数据
            ->fetch();
    }

    /**
     * 添加套餐
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            $result = $this->validate($data, 'Package');

            if ($result!=true)$this->error($result);

            $info = Package_Model::get(['name'=>$data['name']]);

            if ($info)$this->error('套餐名已经存在');

            if ($page = Package_Model::create($data)) {

                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        } else {
            return ZBuilder::make('form')
                ->addFormItems([
                        ['text', 'sort','','','',['排序号:']],
                        ['text', 'name','','','',['套餐名称:']],
                        ['text', 'price', '','','',['套餐价格:']],
                        ['radio','type','套餐组合方式:','',[1=>'同房间组合',2=>'同手牌组合',3=>'同账单组合']],
                    ])
                ->setPageTitle('添加套餐')
                ->fetch();
        }
    }


    /**
     * 编辑套餐
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = null)
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Package');

            if (true !== $result) $this->error($result);


            if (Package_Model::where('id',$id)->update($data)) {
                $this->success('编辑成功', 'index');
            } else {
                $this->error('编辑失败');
            }
        } else {
            $info = Package_Model::get($id);
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['text', 'sort','','','',['排序号:']],
                        ['text', 'name','','','',['套餐名称:']],
                        ['text', 'price', '','','',['套餐价格:']],
                        ['radio','type','套餐组合方式:','',[1=>'同房间组合',2=>'同手牌组合',3=>'同账单组合']],
                    ]
                )
                ->setFormData($info)
                ->setPageTitle('编辑套餐')
                ->fetch();
        }
    }

    /**
     * 添加套餐关联的商品或者项目
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function addItem($id=null)
    {
        if ($this->request->isPost())
        {
            $data = $this->request->post();

            $arr = [];

            if ($data['type']=='goods')
            {
                $goods_info = Goods_Model::get(['id'=>$data['goods_id']]);

                $arr['name'] = $goods_info['name'];
                $arr['price'] = $goods_info['price'];
            }elseif ($data['type']=='project')
            {
                $project_info = Project_Model::get(['id'=>$data['project_id']]);

                $arr['name'] = $project_info['name'];
                $arr['price'] = $project_info['price'];

            }

            $arr['package_id'] = $data['package_id'];
            $arr['item_id'] = $data['type']=="goods"?$data['goods_id']:$data['project_id'];
            $arr['item_type'] = $data['type'];
            $arr['number'] = $data['number'];

            $item_info = Item_Model::get(['item_id'=>$arr['item_id'],'item_type'=>$arr['item_type']]);

            if ($item_info)
            {
                $item_info->number = $item_info['number']+$arr['number'];

                $result = $item_info->save();
            }else{
                $result = Item_Model::create($arr);
            }

            $result?$this->success('操作成功','index'):$this->error('操作失败');

        }

        $goods_list = Goods_Model::column('id,name');

        $project_list = Project_Model::column('id,name');

        return ZBuilder::make('form')
            ->addHidden('package_id',$id)
            ->addRadio('type','请选择项目:','',['goods'=>'商品','project'=>'项目'])
            ->addSelect('goods_id', '请选择商品', '', $goods_list)
            ->addSelect('project_id', '请选择项目', '', $project_list)
            ->setTrigger('type', 'goods', 'goods_id')
            ->setTrigger('type', 'project', 'project_id')
            ->addNumber('number', '数量', '', '', '0', '100')
            ->setFormData()
            ->setPageTitle('编辑项目')
            ->fetch();
    }

    /**
     * 包含的项目或者商品列表
     * @param $id
     * @return mixed
     * @throws \think\Exception
     */
    public function itemLists($id)
    {

        $list = Item_Model::where('package_id',$id)->select();

        foreach ($list as $k=>$v)
        {
            if ($v['item_type']=='goods')
            {
                $list[$k]['name'] = $v['name'].'/商品';
            }elseif ($v['item_type']=='project')
            {
                $list[$k]['name'] = $v['name'].'/项目';

            }
        }


        //设置页面
        return ZBuilder::make('table')
            ->addColumn('id', 'ID', 'text')
            ->addColumn('name', '套餐名称', 'text')
            ->addColumn('price', '项目价格', 'text')
            ->addColumn('number', '数量', 'text')
            ->setTableName('qt_data_package_item')// 指定数据表名
            ->addTopButton('delete')
            ->setPrimaryKey('id')// 设置主键名为username
            ->setPageTitle('套餐列表')
            ->setRowList($list)// 设置表格数据
            ->fetch();
    }

    /**
     * 删除套餐里包含的项目或者商品
     * @param $id
     */
    public function delItem($id)
    {

       if ( Item_Model::destroy($id))
       {
           $this->success('操作成功','index');
       }else{
           $this->error('删除失败');
       }
    }

}